let websocketUrl = 'ws://162.14.82.204:8080/joinMatch';
let websocket = new WebSocket(websocketUrl);

var state = 0 ;
var roomid= "";
function pp() {
    if(state == 1){
        let userid = $("#userid").val(); // 假设这是你的userid
        let message = {
            userid: userid,
            state: '1',
            type: '1'
        };
        websocket.send(JSON.stringify(message)); // 将userid转换为JSON字符串并发送
    }else if(state == 2){
        let userid = $("#userid").val(); // 假设这是你的userid
        let message = {
            userid: userid,
            state: '-1',
            type: '1'
        };
        websocket.send(JSON.stringify(message)); // 将userid转换为JSON字符串并发送
    }else if(state == 3){
        location.replace("/jump/goWuZiQiRoom");
    }
}

websocket.onopen = function(event) {
    console.log("Connected to WebSocket server.");
    let userid = $("#userid").val(); // 假设这是你的userid
    let message = {
        userid: userid,
        state: '0',
        type: '1'
    };
    websocket.send(JSON.stringify(message)); // 将userid转换为JSON字符串并发送
};

websocket.onerror = function(event) {
    console.error("WebSocket error:", event);
    if (event.target.readyState === WebSocket.CLOSED) {
        console.error("Connection closed with error:", event.reason);
    }
};

websocket.onclose = function(event) {
    console.log("WebSocket connection closed:", event);
    let userid = $("#userid").val(); // 假设这是你的userid
    let message = {
        userid: userid,
        state: '-2',
        type: '1'
    };
    websocket.send(JSON.stringify(message)); // 将userid转换为JSON字符串并发送
};

websocket.onmessage = function(event) {
    var data = JSON.parse(event.data);
    if(data.retCode == '0000'){
        if(data.retDesc == '正在匹配'){
            $("#pp_btn").text("正在匹配");
            state = 2;
        }else if(data.retDesc == '取消匹配' || data.retDesc == '上线成功!'){
            $("#pp_btn").text("开始匹配");
            state = 1;
        }else if(data.retDesc == '匹配成功'){
            data.retDesc = "匹配成功,请尽快进入房间!";
            roomid = data.retDesc1;
            $("#pp_btn").text("进入房间");
            state = 3;
        }
    }
    alert(data.retDesc);
};

